package com.fingard.dsp.bank.directbank.chanpay01;

import java.io.File;
import java.io.FileInputStream;
import java.io.RandomAccessFile;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.fingard.FGBiz;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.IStatement;
import com.fingard.dsp.bank.directbank.chanpay01.chanpay01Util.CjSignHelper;
import com.fingard.dsp.bank.directbank.chanpay01.chanpay01Util.HttpPostBodyMethod;
import com.fingard.dsp.bank.directbank.chanpay01.chanpay01Util.Util;
import com.fingard.dsp.bank.reqrespobj.single.detail.RetAtsSglDetail;
import com.fingard.dsp.bank.reqrespobj.statement.ReqQryStatement;
import com.fingard.dsp.bank.reqrespobj.statement.RetAtsStatement;
import com.fingard.dsp.bank.reqrespobj.statement.TransState;
import com.fingard.dsp.bank.reqrespobj.statement.detail.RetAtsStatementDetail;
import com.fingard.text.StringHelper;

public class ChanPay01Statement extends ChanPay01Base implements IStatement{

	@Override
	public RetAtsStatement d_Qry_Statement(ReqQryStatement p_reqQrySttm) {
		// 返回ATS的对象
		RetAtsStatement retAts = new RetAtsStatement(p_reqQrySttm);
		
			
		
		ActSetItem actItem = getBankConfig().getActSetItem(p_reqQrySttm.actNum, "");
		if (actItem == null) {
			RetAtsSglDetail tmpRetDetail = new RetAtsSglDetail();
			tmpRetDetail.respCode = "0";
			tmpRetDetail.respInfo = "未找到账号" + p_reqQrySttm.actNum + "的配置";
			tmpRetDetail.reqSeqID = p_reqQrySttm.actNum;
			tmpRetDetail.transState = PaymentState.FAIL_Batch;
			tmpRetDetail.payInfoCode = "E9981";
			retAts.writeEnd();
			return retAts;
		}
		
		Document doc = DocumentHelper.createDocument();
		Element msgEl = doc.addElement("MESSAGE");

		Element infoEl = msgEl.addElement("INFO");
		infoEl.addElement("TRX_CODE").setText("G40003");
		infoEl.addElement("VERSION").setText("01");
		infoEl.addElement("MERCHANT_ID").setText(actItem.merchantId);
		infoEl.addElement("REQ_SN").setText(p_reqQrySttm.reqHeader.transSeqID);
		infoEl.addElement("TIMESTAMP").setText(Util.getCurrentTimestamp());
		infoEl.addElement("SIGNED_MSG").setText("");

		Element bodyEl = msgEl.addElement("BODY");
		bodyEl.addElement("BILL_TYPE").setText("00");//普通 00
		
		bodyEl.addElement("BILL_DAY").setText(p_reqQrySttm.busDate);
	
		String cjReqmsg = Util.formatXml_UTF8(doc);
		this.WriteBankLogLn("产生G40003对账文件下载：" + Util.substringByByte(cjReqmsg, 512));
		String tmpRespCode = "-1";
		String tmpRespInfo = "";
		
		try {
		CjSignHelper singHelper = new CjSignHelper(actItem);
		String signMsg = singHelper.signXml$Add(cjReqmsg);
		HttpClient client = new HttpClient();
		client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, getCharset());
		client.getParams().setSoTimeout(10 * 60 * 1000);

		URL url = new URL(bankFront.serverURL);
		String urlstr = url.toString();
		HttpPostBodyMethod post = new HttpPostBodyMethod(urlstr, signMsg);

		int statusCode = client.executeMethod(post);
		if (statusCode != HttpStatus.SC_OK) {
			String err = "访问失败！！HTTP_STATUS=" + statusCode;
			throw new HttpException(err);
		}//if
		if(Util.findHeaderAttr(post.getResponseHeader(Util.PROP_NAME_RET_CODE)).equals("0000")){
			//成功
			tmpRespCode = "0";
			SimpleDateFormat sdft = new SimpleDateFormat("yyyy-MM\\dd\\HH");
    		String dateStr = sdft.format(new Date());
    		String tmpRecFolder = FGBiz.dspCenter.rootDirPath+"\\receive\\ChanPay01"+"\\"+dateStr;
    		String zipFilepath = Util.findHeaderAttr(post.getResponseHeader("Content-Disposition")).substring(Util.findHeaderAttr(post.getResponseHeader("Content-Disposition")).indexOf("=")+1, 
    				Util.findHeaderAttr(post.getResponseHeader("Content-Disposition")).indexOf("."));
    		String tmpRecFileName = tmpRecFolder + "\\" + zipFilepath+".zip";
    		tmpRecFileName = tmpRecFileName.replace("\\", "\\\\");
    		String path = tmpRecFileName.substring(0, tmpRecFileName.lastIndexOf("\\"));
			File file = new File(path);//为了创建文件夹，避免FileNotFoundException异常
			if(!file.exists()){
				file.mkdirs();
			}
			else{
			}
			RandomAccessFile raf = new RandomAccessFile(tmpRecFileName,"rw");
			raf.write(post.getResponseBody());
			raf.close();
			tmpRecFolder += "\\"+zipFilepath;
			String tmpUpZipFolder = tmpRecFolder.replace("\\", "\\\\");
			int tmpFolderCount = 0;
			String zipPath = tmpUpZipFolder;
			File f = new File(zipPath);
			while(f.exists()){
				//暂时只考虑同时查询0-9次，超过需要写if
				tmpFolderCount++;
				f = new File(zipPath+"_0"+tmpFolderCount);
			}
			f.mkdirs();
			if(tmpFolderCount>0){
				zipPath = zipPath+"_0"+tmpFolderCount;
			}
			try {
				Util.upzipFile(tmpRecFileName,zipPath+"\\");
			} catch (Exception e) {
				e.printStackTrace();
			}
			String tmpRecResult = zipPath + "\\"+"\\"+zipFilepath+".xls";
			HSSFWorkbook hssfworkbook = new HSSFWorkbook(new FileInputStream(tmpRecResult));
			HSSFSheet    hssfsheet    = hssfworkbook.getSheetAt(0);
			Map<String,Integer> mapHead = new HashMap<String,Integer>();
			Map<String,Integer> mapBody = new HashMap<String,Integer>();
			int rows = hssfsheet.getLastRowNum();
			int detailCount = 0;//实际读到的明细节点数
			int xlsCount = 0;//Excel表中的明细节点数
			if(rows>0){
			 for(int k=0;k<=rows;k++)
	         {		
	        	 RetAtsStatementDetail retDetail = new RetAtsStatementDetail();
	                HSSFRow hssfrow = hssfsheet.getRow(k);
	                if(k==0||k==2){
	                for(int j=0;j<hssfrow.getLastCellNum();j++)
	                {	
	                    HSSFCell hssfcell = hssfrow.getCell(j);
	                    if(k==0){
	                    	mapHead.put(hssfcell.getStringCellValue(), j);
	                    }
	                    if(k==2){
	                    	mapBody.put(hssfcell.getStringCellValue(), j); //读Excel表记录名称、列数
	                    }
	                }
	               }
	                if(k==1){//读取明细条数
	                	xlsCount = (int) hssfrow.getCell(mapHead.get("明细条数")).getNumericCellValue();
	                }
	               if(k>2){
	            	   detailCount++;
	            	   if(mapBody.get("批次编号")<=(hssfrow.getLastCellNum())){//防止空指针异常
	            		   retDetail.reqBatchNO = hssfrow.getCell(mapBody.get("批次编号")).getStringCellValue();
	            	   }
	            	   if(mapBody.get("明细编号")<=(hssfrow.getLastCellNum())&&!StringHelper.isNullOrEmpty(hssfrow.getCell(mapBody.get("明细编号")).getStringCellValue())){
	            		   //批量
	            		   retDetail.askNumber = hssfrow.getCell(mapBody.get("明细编号")).getStringCellValue();
	            	   }
	            	   else if(mapBody.get("批次编号")<=(hssfrow.getLastCellNum())){//单笔
	            		   retDetail.askNumber = hssfrow.getCell(mapBody.get("批次编号")).getStringCellValue();
	            	   }
	            	   if(mapBody.get("对方账号")<=(hssfrow.getLastCellNum())){
	            		   retDetail.oppAct = hssfrow.getCell(mapBody.get("对方账号")).getStringCellValue();
	            	   }
	            	   if(mapBody.get("对方账户名称")<=(hssfrow.getLastCellNum())){
	            		   retDetail.oppActName = hssfrow.getCell(mapBody.get("对方账户名称")).getStringCellValue();
	            	   }
	            	   if(mapBody.get("币种")<(hssfrow.getLastCellNum())){
	            		   retDetail.cur = hssfrow.getCell(mapBody.get("币种")).getStringCellValue();
	            	   }
	            	   if(mapBody.get("交易金额")<=(hssfrow.getLastCellNum())){
	            		   retDetail.amount = hssfrow.getCell(mapBody.get("交易金额")).getStringCellValue();
	            	   }
	            	   if(mapBody.get("交易状态")<=(hssfrow.getLastCellNum())&&"1000".equals(hssfrow.getCell(mapBody.get("交易状态")).getStringCellValue())){
	            		   retDetail.transState=TransState.Success;
	            	   }
	            	   else{
	            		   retDetail.transState=TransState.Fail;
	            	   }
	            	   if(mapBody.get("交易提交时间")<=(hssfrow.getLastCellNum())){
	            		   retDetail.busTime = hssfrow.getCell(mapBody.get("交易提交时间")).getStringCellValue();
	            	   }
	               }
	                if(k>2){//为了避免读Excel表中文时加入空节点
	                	retAts.writeRetDetail(retDetail);
	                }
	         }
			 if(xlsCount!=detailCount){
				 tmpRespCode = "-1";
				 tmpRespInfo="明细条数实际读取不对应";
			 }
	        }
	         else{
	        	 //文件内容空
	        	tmpRespCode = "-1";
				tmpRespInfo = "返回文件内容无总交易单数";
	         }
		}
		else{
			//获取对账单文件失败
			tmpRespCode = "-1";
			tmpRespInfo = "获取对账单失败:"+Util.findHeaderAttr(post.getResponseHeader(Util.PROP_NAME_ERR_MSG));
			
		}
		
		} catch (Exception e) {
			tmpRespCode = "-1";
			e.printStackTrace();
			tmpRespInfo = e.getMessage();
			this.WriteBankLogLn(e);
		}
		try{
			if(tmpRespCode.equals("-1")){
				retAts = new RetAtsStatement(p_reqQrySttm);
				retAts.writeStart();//写返回ATS的统一头部信息
				retAts.writeRespCode(tmpRespCode);
				retAts.writeRespInfo(tmpRespInfo);
			}
			else if(retAts.getWrittenRdCount() == 0){
				retAts.writeRespCode("0");
				if(StringHelper.isNullOrEmpty(tmpRespInfo)){
					tmpRespInfo = "交易为空";
				}
				retAts.writeRespInfo(tmpRespInfo);
			}
		}
		catch(Exception ex){
			this.WriteBankLogLn(ex);
		}
		retAts.writeEnd();
		return retAts;
	}
	
}
